package com.liuyi.pay.wx;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.IpKit;
import com.ijpay.core.kit.QrCodeKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.model.OrderQueryModel;
import com.ijpay.wxpay.model.RefundModel;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import com.liuyi.tools.kits.LocalDateTimeKit;
import com.liuyi.tools.web.unusual.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * <p>
 * 微信支付
 * </p>
 *
 * @author Mr.Fmy
 * @since 2020-11-26
 */
@Service
@Slf4j
public class WxPayService {

    /**
     * 微信支付查询
     * 返回数据可以参考文档：https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_2
     */
    public Map<String, String> searchPay(String appid, String out_trade_no) {
        return searchPay(appid, out_trade_no, null);
    }

    /**
     * 微信支付查询
     * 返回数据可以参考文档：https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_2
     */
    public Map<String, String> searchPay(String appid, String out_trade_no, String transaction_id) {
        WxPayApiConfig apiConfig = WxPayApiConfigKit.getApiConfig(appid);
        Map<String, String> params = OrderQueryModel.builder()
                .appid(appid)
                .mch_id(apiConfig.getMchId())
                .out_trade_no(out_trade_no)
                .transaction_id(transaction_id)
                .nonce_str(WxPayKit.generateStr())
                .build()
                .createSign(apiConfig.getPartnerKey(), SignType.HMACSHA256);

        String resultXml = WxPayApi.orderQuery(params);
        return resultMap(resultXml);
    }

    /**
     * 支付通知
     */
    public String payNotify(HttpServletRequest request, Function<Dict, Boolean> function) {
        String xmlMsg = HttpKit.readData(request);
        log.info("支付通知=" + xmlMsg);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);

        String returnCode = params.get("return_code");
        String appid = params.get("appid");

        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getApiConfig(appid).getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                // 更新订单信息
                Dict dict = new Dict();
                dict.put("transaction_id", params.get("transaction_id"));
                dict.put("out_trade_no", params.get("out_trade_no"));
                dict.put("attach", params.get("attach"));
                dict.put("total_fee", params.get("total_fee"));
                dict.put("appid", appid);
                if (function.apply(dict)) {
                    // 发送通知等
                    Map<String, String> xml = new HashMap<String, String>(2);
                    xml.put("return_code", "SUCCESS");
                    xml.put("return_msg", "OK");
                    return WxPayKit.toXml(xml);
                }
            }
        }
        return null;
    }

    /**
     * 微信扫码支付，模式二
     *
     * @param placeTime 下单时间
     */
    public void scanCode2(String appid, String body, String attach, String orderNo, BigDecimal amount, String notifyUrl,
                          LocalDateTime placeTime, LocalDateTime expireTime, HttpServletRequest request, HttpServletResponse response) {
        String ip = IpKit.getRealIp(request);
        if (StrUtil.isBlank(ip)) {
            ip = "127.0.0.1";
        }
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getApiConfig(appid);
        Map<String, String> params = UnifiedOrderModel
                .builder()
                .appid(wxPayApiConfig.getAppId())
                .mch_id(wxPayApiConfig.getMchId())
                .nonce_str(WxPayKit.generateStr())
                .body(body)
                .attach(attach)
                .out_trade_no(orderNo)
                .total_fee(amount.multiply(new BigDecimal(100)).setScale(0).toString())
                .spbill_create_ip(ip)
                .notify_url(wxPayApiConfig.getDomain() + notifyUrl)
                .time_start(LocalDateTimeKit.formatLocalDateTime(placeTime))
                .time_expire(LocalDateTimeKit.formatLocalDateTime(expireTime))
                .trade_type(TradeType.NATIVE.getTradeType())
                .build()
                .createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);
        String xmlResult = WxPayApi.pushOrder(false, params);
        log.info("统一下单:" + xmlResult);
        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);
        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        System.out.println(returnMsg);
        if (!WxPayKit.codeIsOk(returnCode)) {
            throw new BizException("error:" + returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            throw new BizException("error:" + result.get("err_code_des"));
        }
        //生成预付订单success
        String qrCodeUrl = result.get("code_url");
        try {
            QrCodeKit.encodeOutPutSteam(response.getOutputStream(), qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200);
        } catch (IOException e) {
            log.error("微信扫码支付二维码转换失败：" + e.getMessage(), e);
            throw new BizException("发起支付失败，请稍后");
        }
    }


    /**
     * 微信退款
     */
    public Map<String, String> refund(String appid, String transactionId, String outTradeNo, BigDecimal totalFee, BigDecimal refundFee) {
        WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getApiConfig(appid);
        Map<String, String> params = RefundModel.builder()
                .appid(wxPayApiConfig.getAppId())
                .mch_id(wxPayApiConfig.getMchId())
                .nonce_str(WxPayKit.generateStr())
                .transaction_id(transactionId)
                .out_trade_no(outTradeNo)
                .out_refund_no(WxPayKit.generateStr())
                .total_fee(totalFee.multiply(BigDecimal.valueOf(100)).setScale(0).toString())
                .refund_fee(refundFee.multiply(BigDecimal.valueOf(100)).setScale(0).toString())
                .build()
                .createSign(wxPayApiConfig.getPartnerKey(), SignType.MD5);
        String refundStr = WxPayApi.orderRefund(false, params, wxPayApiConfig.getCertPath(), wxPayApiConfig.getMchId());
        return resultMap(refundStr);
    }

    private Map<String, String> resultMap(String xmlResult) {
        Map<String, String> result = WxPayKit.xmlToMap(xmlResult);
        String returnCode = result.get("return_code");
        String returnMsg = result.get("return_msg");
        if (!WxPayKit.codeIsOk(returnCode)) {
            throw new BizException("error:" + returnMsg);
        }
        String resultCode = result.get("result_code");
        if (!WxPayKit.codeIsOk(resultCode)) {
            throw new BizException("error:" + result.get("err_code_des"));
        }
        return result;
    }
}
